import random
import time
import threading

from tlv import tlv_parser_hw
from utils import util_socket


class SendPackage(object):
    def __init__(self, ip, port):
        self.service_info = {"ip": ip, "port": port}

    def test_order(self, ip_list):
        a = time.time()
        sender = util_socket.SocketUtils()
        for ip in ip_list:
            data = {"type": 3, "serial_no": random.randint(0, 65535), "user_ip": ip,
                    "attr": {"username": "zyt", "password": "123456"}, "secret": "123456789"}
            tb = tlv_parser_hw.TlvBuilderHw(data)
            data_package = tb.build_data()
            result = sender.socket_client(self.service_info, data_package)
            print(result)
        print(time.time() - a)

    def test_thread(self, ip_list):
        a = time.time()
        b = {}
        for ip in ip_list:
            data = {"type": 3, "serial_no": random.randint(0, 65535), "user_ip": ip,
                    "attr": {"username": "zyt", "password": "123456"}, "secret": "123456789"}
            b[ip] = SendThread(data, self.service_info)
            b[ip].start()
        for i in b:
            b[i].join()
        print(time.time() - a)


class SendThread(threading.Thread):
    def __init__(self, data, service_info):
        threading.Thread.__init__(self)
        self.data = data
        self.service_info = service_info

    def run(self):
        print("开始发送%s的联网包" % self.data["user_ip"])
        self.send()

    def send(self):
        sender = util_socket.SocketUtils()
        tb = tlv_parser_hw.TlvBuilder(self.data)
        data_package = tb.build_data()
        result = sender.socket_client(self.service_info, data_package)
        print(result)


if __name__ == "__main__":
    a = SendPackage("192.168.1.199", 2000)
    ip_list = ["192.168.1.193", "192.168.1.149", "192.168.1.189", "192.168.1.194", "192.168.1.181"]
    for i in range(1,11):
        ip_list.append("192.168.1.193")
    # 使用多线程发包
    a.test_thread(ip_list)
    # 使用单线程发包
    # a.test_order(ip_list)
